<template>
  <el-dialog
    v-el-drag-dialog
    title="编辑用户角色"
    :visible.sync="visible"
    width="450px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
      <el-form-item label="用户名称:" prop="userName">
        <el-input v-model="temp.userName" disabled />
      </el-form-item>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        border
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        :height="400"
        @fetch="fetchData"
        @selection-change="handleSelectionChange"
      />
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { userQueryRolesList, queryUserRoles, saveUserRoles } from '@/api'

  export default {
    name: 'edit-role',
    data() {
      return {
        visible: false,
        userRoles: [],
        temp: {
          userName: ''
        },
        tableData: {
          data: [],
          column: [
            {
              type: 'selection'
            },
            {
              prop: 'roleName',
              label: '角色名称'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ]
        },
        multipleSelection: []
      }
    },
    watch: {
      userRoles: {
        handler() {
          this.$nextTick(() => {
            this.toggleSelection()
          })
        },
        deep: true
      },
      'tableData.data': {
        handler() {
          this.$nextTick(() => {
            this.toggleSelection()
          })
        },
        deep: true
      }
    },
    methods: {
      async open(temp) {
        await this.getUserRoles(temp)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      // 查询用户现有的角色
      async getUserRoles(temp) {
        const res = await queryUserRoles({ userId: temp.userId })
        this.userRoles = res.data
      },
      async fetchData() {
        const query = {
          currentPage: 1,
          pageSize: 999,
          userId: this.temp.userId
        }
        const res = await userQueryRolesList(query)
        // this.$set(this.tableData, 'data', res.data.rows)
        this.tableData.data = res.data.rows
      },
      toggleSelection() {
        const rows = this.tableData.data.filter(item => this.userRoles.find(it => it.roleId === item.roleId))
        console.log(this.$refs.lbTable, this.tableData.data, this.userRoles, rows, 1111111)
        this.multipleSelection = rows
        if (rows.length > 0) {
          rows.forEach(row => {
            this.$refs.lbTable.toggleRowSelection(row)
          })
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      async success() {
        const roleIdsArr = this.multipleSelection.map(item => item.roleId)
        const roleNamesArr = roleIdsArr.map(item => {
          const match = this.tableData.data.find(it => it.roleId === item)
          return match.roleName
        })
        const params = {
          userId: this.temp.userId,
          roleIds: roleIdsArr.join(','),
          roleStr: roleNamesArr.join(',')
        }
        await saveUserRoles(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '保存用户角色成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.temp = {
          userName: ''
        }
        this.$refs.lbTable.clearSelection()
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
